<?php
class WebsController extends AppController {
    var $name = 'Webs';
    var $helpers = array('Html', 'Form','Box', 'Pagination','Fck','Calendar');
    var $components = array('Domini');
    var $uses = array('Album','Image','Event','Calendar','Web', 'Organization', 'Video', 'Noticia','Cmsconfiguration','Profile','Arquivo');
    
    function index (){
    	$this->redirect('/users/home/');    
    }
     
    function index_atividade()
    {
        $title = 'Visualizar Atividades';
        $this->set('title', $title);
        $this->set('pageTitle', $title);
        
        $organization=$this->othAuth->getData('organization');
    	$organization = $this->Web->Organization->find(array('Organization.id' => $organization['id']));
        $this->set('web', $organization['Web']);
    }
    
    function edit_atividade()
    {
        $title = 'Editar Atividades';
        $this->set('title', $title);
        $this->set('pageTitle', $title);

        $organization=$this->othAuth->getData('organization');
    	$organization = $this->Web->Organization->find(array('Organization.id' => $organization['id']));
        $this->set('web', $organization['Web']);
    }
    
    function add_atividade($id = null)
    {
	if (!empty($this->data)) {
		$organizationUser = $this->othAuth->getData('unit');
	
	$organization=$this->othAuth->getData('organization');
    	$organization = $this->Web->Organization->find(array('Organization.id' => $organization['id']));

        if (isset($organization['Web'])) {
		$this->Web->id = $organization['Web']['id'];
		$this->data['Web']['id'] = $organization['Web']['id'];
	}

	if ($this->Web->save($this->data)) {
		if (!isset($this->data['Web']['id'])) {
			$web_id = $this->Web->getLastInsertId();
			$this->data['Organization']['id'] = $organizationUser['0']['Organization']['id'];
			$this->data['Organization']['web_id'] = $web_id;
			if ($this->Organization->save($this->data)) {
				$_SESSION['mensagem']['success'][] = 'Atividade cadastrada com sucesso!';
			} else {
				$_SESSION['mensagem']['error'][] = 'Erro ao tentar cadastrar Atividade.';
			}
		}
		
            } else {
                $_SESSION['mensagem']['error'][] = 'Erro ao tentar cadastrar Atividade.';
            }
            $this->redirect('/webs/index_atividade/');
        }
    }
    
      function index_apoio()
    {
        $title = 'Visualizar Apoio';
        $this->set('title', $title);
        $this->set('pageTitle', $title);

        $organization=$this->othAuth->getData('organization');
    	$organization = $this->Web->Organization->find(array('Organization.id' => $organization['id']));
        $this->set('web', $organization['Web']);
    }
    
    function edit_apoio()
    {
        $title = 'Editar Apoio';
        $this->set('title', $title);
        $this->set('pageTitle', $title);

        $organization=$this->othAuth->getData('organization');
    	$organization = $this->Web->Organization->find(array('Organization.id' => $organization['id']));
        $this->set('web', $organization['Web']);
    }
    
    function add_apoio($id = null)
    {
    	if (!empty($this->data)) {
            $organizationUser = $this->othAuth->getData('unit');

	$organization=$this->othAuth->getData('organization');
    	$organization = $this->Web->Organization->find(array('Organization.id' => $organization['id']));

        if (isset($organization['Web'])) {
		$this->Web->id = $organization['Web']['id'];
		$this->data['Web']['id'] = $organization['Web']['id'];
	}

	if ($this->Web->save($this->data)) {
		if (!isset($this->data['Web']['id'])) {
			$web_id = $this->Web->getLastInsertId();
		
			$this->data['Organization']['id'] = $organizationUser['0']['Organization']['id'];
			$this->data['Organization']['web_id'] = $web_id;

			if ($this->Organization->save($this->data)) {
				$_SESSION['mensagem']['success'][] = 'Apoio cadastrado com sucesso!';
			} else {
				$_SESSION['mensagem']['error'][] = 'Erro ao tentar cadastrar Apoio.';
			}
		}
            } else {
                $_SESSION['mensagem']['error'][] = 'Erro ao tentar cadastrar Apoio.';
            }
            $this->redirect('/webs/index_apoio/');
        }
    }
    
    function add_download(){
    	if (!empty($this->data)) {
		$photo = $this->params["data"]["Download"]["photo"];
		if($photo["size"]>0){
			$fileData = fread(fopen($photo["tmp_name"],"r"),$photo["size"]);
			$this->params["data"]["Download"]["photo"] = $fileData;
		}else{
			$this->params["data"]["Download"]["photo"] = null;
		}
		if(!$this->Volunteer->User->save($this->params["data"])){
			$_SESSION['mensagem']['error'][] = 'Erro ao tentar salvar a foto.';
		}
	}
    }

	function calendar($calendar=null,$tag=null,$date=null) {
		$title = 'Calendário de Eventos da Entidade';
		$this->set('title', $title);
		$this->set('pageTitle', $title);
		
		// Permissao: se pode visualizar todas as unidades
		$group = $this->othAuth->getData('group');
		$level =$group['level'];
		$unitUser = $this->othAuth->getData('unit');
		$conditions = array();
		$organization_id = null;
		if ($level >= 100) {  // not system admin
			$organization_id = $unitUser['0']['Organization']['id'];
		}
		
		// Recupera informacoes
		$date = $this->Domini->parseUrl($calendar,$tag,$date);
		$prev = $this->Domini->findPrev($this->params['pass']);
		$next = $this->Domini->findNext($this->params['pass']);

		$events = $this->Event->findPublicEvents($date,$organization_id);
		$date['calendar_name'] = $this->requestAction('/calendars/findNameByShortname/'.$calendar);
		$date['tag_name'] = $this->requestAction('/tags/findNameByShortname/'.$tag);

		$this->set(compact('events','prev','next','date'));
	}

	function albuns() {
		$title = 'Álbuns';
		$this->set('title', $title);
		$this->set('pageTitle', $title);

		$conditions = array();

		// Recuperando ID do usuário logado
		$user = $this->othAuth->getData("user");
		$user_id = $user['id'];

		// Permissao: se pode visualizar todas as unidades
		$group = $this->othAuth->getData('group');
		$level =$group['level'];
		$unitUser = $this->othAuth->getData('unit');

		$conditions1 = array();
		if ($level >= 100) {  // not system admin
			$conditions1[] = array("organization_id"=>$unitUser['0']['Organization']['id']);
		}
		// Recuperando álbuns da Entidade
		$albums      = $this->Album->find('all',array("conditions"=>$conditions1,'order'=>'Album.Data DESC'));

		// Passando variáveis para a UI
		$this->set('albums', $albums);
	}


/*************************************************************/
/* Front end functions */
/*************************************************************/
	function front_home($id) {
		$organization = $this->Organization->find('first', array('conditions' => array('Organization.alias' => $id)));
		$this->set('organization', $organization);

		$cmsconfiguration = $this->Cmsconfiguration->find('first', array('Organization.id' => $organization['Organization']['cmsconfiguration_id']));
		
		$this->set('cmsconfiguration', $cmsconfiguration);
		
		/* Msg Perfil */
		if($cmsconfiguration['Cmsconfiguration']['visible_msg_perfil']==true){
			$web = $this->Web->find(array('Web.id' => $organization['Organization']['web_id']));
			$this->set('web', $web);	
		}		
		/* Videos */
		if($cmsconfiguration['Cmsconfiguration']['visible_video']==true){
			$video = $this->Video->find('first', array('conditions' => array('Video.organization_id' => $organization['Organization']['id']), 'order' => array('Video.id DESC') ));
			$last_video = $video['Video'];
			$this->set('last_video', $last_video);
			$duration="".(($last_video['duration']-$last_video['duration']%60)/60) . ":" .sprintf("%02d",$last_video['duration']%60);
			$this->set('duration', $duration);
		}
		/* Noticias */
		if($cmsconfiguration['Cmsconfiguration']['visible_news']==true){
			$conditions = array();
			$conditions[] = array('Noticia.organization_id' => $organization['Organization']['id']);
			$conditions[] = array('Noticia.published' => '1');
			$conditions[] = array('Noticia.public' => '1');
			
			$noticias = $this->Noticia->find('all', array('conditions'=>$conditions, 'order' => array('Noticia.publishedon DESC'), 'limit' => 3 ));
			foreach ($noticias as $k=>$noticia) {
				$link = "/site/".$organization['Organization']['alias']."/noticias/".$noticia['Noticia']['id'];
				$link = Router::url($link, true);
				$noticias[$k]['Noticia']['link'] = $link;
			}
			//pr($organization);
			$this->set('noticias', $noticias);
		}
		/* Eventos */
		if($cmsconfiguration['Cmsconfiguration']['visible_event']==true){
			$conditions = array();
			$conditions[] = array('Event.organization_id' => $organization['Organization']['id']);
			$conditions[] = array('Event.public' => '1');
			$conditions[] = array('Event.date >=' =>  date("Y-m-d"));
			
			$events = $this->Event->find('all', array('conditions'=>$conditions, 'order' => array('Event.date ASC'), 'limit' => 3 ));
			foreach ($events as $k=>$event) {
				$link = "/site/".$organization['Organization']['alias']."/eventos/".$event['Event']['id'];
				$link = Router::url($link, true);
				$events[$k]['Event']['link'] = $link;
			}
			$this->set('events', $events);
		}
		
		/* Album */
		if($cmsconfiguration['Cmsconfiguration']['visible_album']==true){

			$org_id = $organization['Organization']['id'];
			$albums = $this->Album->find('all', array('conditions'=>array('organization_id' => $org_id),'order'=>'Album.Data DESC', 'limit' => 3 ));
		
			foreach ($albums as $k=>$album) {
				$link = "/site/".$organization['Organization']['alias']."/album/".$album['Album']['id'];
				$link = Router::url($link, true);
				$albums[$k]['Album']['link'] = $link;
			}			
			$this->set('albums', $albums);
			
		
		}
	}	
	
	function front_videos_list($id) {
		$organization = $this->Organization->find('first', array('conditions' => array('Organization.alias' => $id)));
		$this->set('organization', $organization);
		
		$videos = $this->Video->find('all', array('conditions' => array('Video.organization_id' => $organization['Organization']['id']), 'order' => array('Video.id DESC') ));
		$this->set('videos', $organization['Video']);
	}
	
	function front_video_view($id, $video_id) {
		$video = $this->Video->find('first', array('conditions' => array('Video.id' => $video_id)));
		$this->set('video', $video);
	}
	
	function front_noticias_list ($id) {
		$organization = $this->Organization->find('first', array('conditions' => array('Organization.alias' => $id)));
		$this->set('organization', $organization);

		/* Noticias */
		$conditions = array();
		$conditions[] = array('Noticia.organization_id' => $organization['Organization']['id']);
		$conditions[] = array('Noticia.published' => '1');
		$conditions[] = array('Noticia.public' => '1');
		$noticias = $this->Noticia->find('all', array('conditions'=>$conditions, 'order' => array('Noticia.publishedon')));
		foreach ($noticias as $k=>$noticia) {
			if (strlen($noticia['Noticia']['text']) > 200) {
				$str_array = str_split($noticia['Noticia']['text'], 200);
				$str = $str_array[0];
				$str = trim($str);
				$str = $str."...";
			} else {
				$str = "";
			}
			$noticias[$k]['Noticia']['snippet'] = $str;
			$link = "/site/".$organization['Organization']['alias']."/noticias/".$noticia['Noticia']['id'];
			$link = Router::url($link, true);
			$noticias[$k]['Noticia']['link'] = $link;
		}
		$this->set('noticias', $noticias);
	}
	
	function front_events_list ($id, $calendar=null,$tag=null,$date=null) {
		$organization = $this->Organization->find('first', array('conditions' => array('Organization.alias' => $id)));
		$this->set('organization', $organization);

		/* Noticias */
		$conditions = array();
		$conditions[] = array('Event.organization_id' => $organization['Organization']['id']);
		$conditions[] = array('Event.public' => '1');
		$events = $this->Event->find('all', array('conditions'=>$conditions, 'order' => array('Event.date')));
		foreach ($events as $k=>$event) {
			$link = "/site/".$organization['Organization']['alias']."/eventos/".$event['Event']['id'];
			$link = Router::url($link, true);
			$events[$k]['Event']['link'] = $link;
		}
		$this->set('events', $events);
		
		// Recupera informacoes
		
		$date = $this->Domini->parseUrl($calendar,$tag,$date);
		
		if (!isset($this->params['pass']['1']))
			$this->params['pass']['1'] = '';
		$prev = $this->Domini->findPrev(array('',$this->params['pass']['1']));
		$next = $this->Domini->findNext(array('',$this->params['pass']['1']));

		$condition = array();
		$condition[] = array('Event.organization_id'=>$organization['Organization']['id']);		
		$condition[] = array('Event.public'=>'1');
		$events = $this->Event->find('all', array('conditions'=>$condition));
		$date['calendar_name'] = $this->requestAction('/calendars/findNameByShortname/'.$calendar);
		$date['tag_name'] = $this->requestAction('/tags/findNameByShortname/'.$tag);
		$this->set('date', $date);
		$this->set('prev', $prev);
		$this->set('next', $next);
		
	}
	
	function front_noticia_view($id, $noticia_id) {
		$noticia = $this->Noticia->find('first', array('conditions' => array('Noticia.id' => $noticia_id)));
		$this->set('noticia', $noticia);
	}
	
	function front_atividades($id) {
		$organization = $this->Organization->find('first', array('conditions' => array('Organization.alias' => $id)));
		$this->set('organization', $organization);
		
        $this->set('web', $organization['Web']);
	}
	
	function front_apoio($id) {
		$organization = $this->Organization->find('first', array('conditions' => array('Organization.alias' => $id)));
		$this->set('organization', $organization);
		
        $this->set('web', $organization['Web']);
	}
	function front_perfil($id) {
		$organization = $this->Organization->find('first', array('conditions' => array('Organization.alias' => $id)));
		$this->set('web', $organization['Organization']);
		$this->set('profile', $organization['Profile']);
		$this->set('cidade',$organization['Cidade']);
		
		$conditions = array('Unit.organization_id' => $organization['Organization']['id']);
		$units = $this->Organization->Unit->find('all', array('conditions'=>$conditions));
		
		$this->set('units', $units);
		
	}
	
	function front_downloads_list($id) {
		$organization = $this->Organization->find('first', array('conditions' => array('Organization.alias' => $id)));
		$arquivos = $this->Arquivo->find('all', array('organization_id' => $organization['Organization']['id']));
		$this->set('arquivos', $arquivos);
	}

	function front_albums_list($id) {

		$organization = $this->Organization->find('first', array('conditions' => array('Organization.alias' => $id)));
		$this->set('organization', $organization);

		$org_id = $organization['Organization']['id'];
		$albums = $this->Album->find('all', array('conditions'=>array('organization_id' => $org_id),'order'=>'Album.Data DESC'));

		foreach ($albums as $k=>$album) {
			$link = "/site/".$organization['Organization']['alias']."/album/".$album['Album']['id'];
			$link = Router::url($link, true);
			$albums[$k]['Album']['link'] = $link;

		$this->set('albums', $albums);
		}

	}

	function front_album_view($id, $album_id) {

		if (!$id) 
			$this->redirect('/webs/albuns');
		$this->set('pageTitle','Visualizar álbum');
			
		$this->Album->id = $album_id;
		$album = $this->Album->read();


		$organization = $this->Organization->find('first', array('conditions' => array('Organization.alias' => $id)));
		$this->set('organization', $organization);

		foreach ($album['Image'] as $k=>$image) {
			
			$link = "/site/".$organization['Organization']['alias']."/image/".$image['id'];
			$link = Router::url($link, true);
			$album['Image'][$k]['link'] = $link;
		}

		$link = "/site/".$organization['Organization']['alias']."/album/";
		$link = Router::url($link, true);
		$album['Album']['return'] = $link;

     	$this->set('album', $album);

	}

	function front_image_view($id, $image_id) {
		if(!$id) {
			// Redirecting to File List     
			$_SESSION['mensagem']['error'][] = 'Imagem inválida!';       
			$this->redirect('/webs/albuns');
		}
		
		$title = 'Visualizar imagem';
		$this->set('title', $title);
		$this->set('pageTitle', $title);

		$organization = $this->Organization->find('first', array('conditions' => array('Organization.alias' => $id)));
		$this->set('organization', $organization);

		$this->Image->id = $image_id;
		$image = $this->Image->read();

		$vizinhos = $this->Image->find('neighbors', array('field' => 'id', 'value' => $image_id,'conditions' => 'album_id='.$image['Image']['album_id']));

		//pr($vizinhos);

		if(count($vizinhos['prev']) > 0) {
			$linkPrev = "/site/".$organization['Organization']['alias']."/image/".$vizinhos['prev']['Image']['id'];;
			$linkPrev = Router::url($linkPrev, true);
			$this->set('prev',$linkPrev);
		}
		
		if(count($vizinhos['next']) > 0) {
			$linkNext = "/site/".$organization['Organization']['alias']."/image/".$vizinhos['next']['Image']['id'];;
			$linkNext = Router::url($linkNext, true);
			$this->set('next',$linkNext);
		}
		
		$link = "/site/".$organization['Organization']['alias']."/album/".$image['Image']['album_id'];
		$link = Router::url($link, true);
		$image['Image']['return'] = $link;

		$this->set('image',$image);
	}

}


